package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.pojo.Dish;
import com.itheima.reggie.pojo.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @title: DishController
 * @Author 椎名真白
 * @Date: 2022-04-29 14:25
 * @Version 1.0
 */

@Slf4j
@RestController
@RequestMapping("dish")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private DishFlavorService dishFlavorService;

    /**
     * @description: 新增菜品 使用了菜品表和菜品口味表在service中进行方法增强
     * @author: 椎名真白
     * @date: 2022-04-29 14:39
     * @param: dishDto
     * @return: com.itheima.reggie.common.R<java.lang.String>
     **/
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {
        dishService.saveWithDishFlavor(dishDto);
 /*       //清理所有分类下的菜品的缓存数据
        Set keys = redisTemplate.keys("dish_");
        //获取dish_开头的数据并删除
        redisTemplate.delete(keys);*/
        //清理当前分类下的菜品缓存
        String key = "dish_" + dishDto.getCategoryId();
        redisTemplate.delete(key);
        return R.success("新增菜品成功");
    }

    @GetMapping("page")
    public R<Page> page(Integer page, Integer pageSize, String name) {
        //构造Dish和DishDto的分页器
        Page<Dish> dishPage = new Page<>(page, pageSize);
        Page<DishDto> dishDtoPage = new Page<>();
        //条件选择器
        QueryWrapper<Dish> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(name != null, "name", name);
        dishService.page(dishPage, queryWrapper);
        BeanUtils.copyProperties(dishPage, dishDtoPage, "records");

        //将List<DISH> 转为DISHDTO集合
        ArrayList<DishDto> dishDtoList = new ArrayList<>();
        for (Dish dish : dishPage.getRecords()) {
            DishDto dishDto = new DishDto();
            //拷贝dish集合到dishDto
            BeanUtils.copyProperties(dish, dishDto);

            //为dishDto中的菜品分类名城赋值
            dishDto.setCategoryName(categoryService.getById(dishDto.getCategoryId()).getName());
            dishDtoList.add(dishDto);
        }
        dishDtoPage.setRecords(dishDtoList);


        /*List<Dish> dishRecords = dishPage.getRecords();
        List<DishDto> records = dishDtoPage.getRecords();
        for (int i = 0; i < dishRecords.size(); i++) {
            BeanUtils.copyProperties(dishRecords, records);
            DishDto dishDto = new DishDto();
            Long categoryId = dishDto.getCategoryId();
            Category category = categoryService.getById(categoryId);
            //dishDto.setCategoryName(categoryService.getById(dishDto.getCategoryId()).getName());
            if (category != null) {
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            records.add(dishDto);
        }
        dishDtoPage.setRecords(records);
*/
        return R.success(dishDtoPage);
    }

    @GetMapping("/{id}")
    public R<DishDto> findById(@PathVariable Long id) {
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

    /**
     * @description: 修改菜品的状态
     * @author: 椎名真白
     * @date: 2022-04-28 20:47
     * @param: status
     * @param: ids
     * @return: com.itheima.reggie.common.R<java.lang.String>
     **/
    @PostMapping("status/{status}")
    public R<String> changeStatus(@PathVariable int status, Long[] ids) {
        //传输的状态码(1/0）即将要改成的状态 批量该如何写 用遍历感觉属实太捞了
        //dishService.update()
       /* QueryWrapper<Dish> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(ids+""),"id",ids);
        Dish dish = dishService.getOne(queryWrapper);
        log.info("要修改菜品信息{}",dish);
        dish.setStatus(status);
        dishService.updateById(dish);
        return R.success("修改成功");*/
        dishService.updateByIds(status,ids);
        return R.success("修改成功");
    }

    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto) {
        log.info(dishDto.toString());
        dishService.updateWithFlavor(dishDto);
        //清理所有分类下的菜品的缓存数据
        Set keys = redisTemplate.keys("dish_");
        //获取dish_开头的数据并删除
        redisTemplate.delete(keys);
        //清理当前分类下的菜品缓存
        /*String key = "dish_" + dishDto.getCategoryId();
        redisTemplate.delete(key);*/
        return R.success("修改菜品成功");
    }

    /**
     * @description: 查询菜品的集合 在新增套餐是显示到页面上
     * @author: 椎名真白
     * @date: 2022-04-30 10:17
     * @param: categoryId
     * @return: com.itheima.reggie.common.R<java.util.List < com.itheima.reggie.pojo.Dish>>
     **/
    @GetMapping("list")
    public R<List<DishDto>> list(Long categoryId) {
        //先查Redis中的缓存 无数据再查数据库
        String key = "dish_" + categoryId;
        List<DishDto> dishDtoListInRedis = (List<DishDto>) redisTemplate.opsForValue().get(key);
        if (dishDtoListInRedis != null) {
            return R.success(dishDtoListInRedis);
        }
        //条件选择器
        QueryWrapper<Dish> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(categoryId != null, "category_id", categoryId);
        List<Dish> list = dishService.list(queryWrapper);
        //将List<Dish> 拷贝到List<DishDto>
        List<DishDto> dishDtoList = new ArrayList<>();
        for (Dish dish : list) {
            DishDto dishDto = new DishDto(); //dishDto= dish + dishflavor
            BeanUtils.copyProperties(dish, dishDto);

            QueryWrapper<DishFlavor> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("dish_id", dish.getId());
            //获取口味集合
            List<DishFlavor> dishFlavorList = dishFlavorService.list(queryWrapper1);
            //将口味集合放入dishDto中
            dishDto.setFlavors(dishFlavorList);
            //将dishDto放入List<DishDto>中
            dishDtoList.add(dishDto);
        }
        //不存在，从数据库查询数据，查完将数据保存在redis中 60分钟删除
        redisTemplate.opsForValue().set(key, dishDtoList, 60, TimeUnit.MINUTES);
        return R.success(dishDtoList);
    }
}
